import { Component, Inject, Injector } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Service } from '@api';
import { SimpleService } from '@api/simple/service/simple.service';
import { STComponent, STData } from '@delon/abc/st';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { environment } from '@env/environment';
import { stringTemplate } from '@shared/utils/string';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SListComponent } from 'src/app/routes/common/list/slist.component';
import { SimpleEditComponent } from '../list/edit/edit.component';

@Component({
  selector: 'app-simple-dynamic-general-list',
  templateUrl: './general.modal.component.html',
})
export class SimpleGeneralcModalComponent extends SListComponent<any, string> {
  code = '';
  isVisible = false;
  title = '';

  constructor(
    public http: _HttpClient,
    public modal: ModalHelper,
    @Inject(SimpleService) public service: Service<any, string>,
    public msgSrv: NzMessageService,
    public router: Router,
    public route: ActivatedRoute,
    public injector: Injector,
  ) {
    super(http, modal, service, msgSrv, SimpleEditComponent);
  }

  ngOnInit() {
    this.code = this.getCode();

    this.http.get(`${environment.simple.ctx}/simpleList/findByCode/${this.code}`).subscribe((res) => {
      if (res.datasourceType == 'URL') {
        this.url = stringTemplate(res.datasourceId, { environment: environment });
      } else if (res.datasourceType == 'SQL') {
        this.url = `${environment.simple.ctx}/simpleList/data/${this.code}`;
      }
      this.setSearchSchema(res);
      this.setToolbars(res);
      this.setColumns(res);
      this.isDataLoad = true;
    });
  }

  setSearchSchema(schema: any) {
    if (schema.queryFormId) {
      this.http.get(`${environment.simple.ctx}/simpleListField/findByListId/${schema.queryFormId}`).subscribe((res) => {
        const properties: any = {};
        res.forEach((e: any) => {
          properties[e.key] = { type: e.type, title: e.title };
        });
        this.searchSchema.properties = properties;
      });
    }
  }

  setToolbars(schema: any) {
    if (schema.toolbarActionId) {
      this.http.get(`${environment.simple.ctx}/simpleActionField/findByActionId/${schema.toolbarActionId}`).subscribe((res) => {
        this.toolbars = res;
      });
    }
  }

  setColumns(schema: any) {
    schema.fields.forEach((item: any) => {
      if (item.code != 'operate_action') {
        this.columns.push({ title: item.name, index: item.code, type: item.type });
      }
    });
  }

  getCode() {
    return (this.code = this.route.snapshot.params.code);
  }
}
